package com.sunday.android.fangdaifu.bukong;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.sunday.android.fangdaifu.bukong.fragment.tab.BaoFragment;
import com.sunday.android.fangdaifu.bukong.fragment.tab.BaoFragment1;
import com.sunday.android.fangdaifu.bukong.fragment.tab.IndexFragment;
import com.sunday.android.fangdaifu.bukong.fragment.tab.MyFragment;
import com.sunday.android.fangdaifu.bukong.fragment.tab.NewsFragment;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.Constants;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.widgets.ViewPager;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.member.base.BaseActivity;
import com.sunday.member.entity.Version;
import com.sunday.member.event.ExitApp;
import com.sunday.member.update.UpdateDialogActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{
    @Bind({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4})
    List<TextView> tabViews;
    @Bind(R.id.content)
    ViewPager viewPager;

    private ArrayList<Fragment> fragments;
    private String[] perms;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        checkPermsAndInitView();
        checkUpdate();
    }

    private void checkUpdate() {
        Call<ResultDO<Version>> call = ApiClient.getApiAdapter().checkVersion(DeviceUtils.getVersionCode(getApplicationContext()),2);
        call.enqueue(new Callback<ResultDO<Version>>() {
            @Override
            public void onResponse(Call<ResultDO<Version>> call, Response<ResultDO<Version>> response) {
                ResultDO<Version> resultDO = response.body();
                if (isFinish) {
                    return;
                }
                if (resultDO != null && resultDO.getCode() == 0) {
                    final Version version = resultDO.getResult();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                            intent.putExtra("version", version);
                            startActivity(intent);
                        }
                    }, 2000);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Version>> call, Throwable t) {

            }
        });
    }

    //检查权限
    private void checkPermsAndInitView(){
        perms = getResources().getStringArray(R.array.perms);
        if (EasyPermissions.hasPermissions(this,perms)){
            initView();
        }else {
            EasyPermissions.requestPermissions(this,"需要存储、定位权限", Constants.REQUEST_PERMS_CODE,perms);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            checkPermsAndInitView();
        }
    }

    //初始化布局
    private void initView(){
        fragments = new ArrayList<>(4);
        fragments.add(new IndexFragment());
        fragments.add(BaoFragment1.newInstance());
        fragments.add(new NewsFragment());
        fragments.add(new MyFragment());
        tabViews.get(0).setSelected(true);
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(4);
    }

    @OnClick(R.id.tab1)
    void tab1(){
        setSelected(0);
    }
    @OnClick(R.id.tab2)
    void tab2(){
        setSelected(1);
    }
    @OnClick(R.id.tab3)
    void tab3(){
        setSelected(2);
    }
    @OnClick(R.id.tab4)
    void tab4(){
        setSelected(3);
    }
    //选中的tab，切换页面
    private void setSelected(int position){
        for (int i = 0; i < tabViews.size(); i++) {
            tabViews.get(i).setSelected(false);
        }
        tabViews.get(position).setSelected(true);
        viewPager.setCurrentItem(position,false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        //权限允许
        if (list.size()==perms.length){//当所有权限都被允许时才初始化
            initView();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        //权限获取失败
        if (EasyPermissions.somePermissionPermanentlyDenied(this, list)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle(R.string.perm_fail)
                    .setRationale(R.string.perm_notice)
                    .setNegativeButton(Constants.PERMS_CANCEL, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(new ExitApp());
                            System.exit(1);
                        }
                    })
                    .setPositiveButton(R.string.perm_setting)
                    .build().show();
        }
    }

    public void setViewPagerIndex(int index){
        setSelected(index);
    }
}
